#!coding: utf-8
# Create your views here.
import sys 
import os
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import json
import socket 

import pymongo

from exceptions import Exception

def sync_user(nick, top_session):
    print 'sync user: ', repr(nick)
    try: 
        sock = socket.socket()
        sock.settimeout(0.5)
        sock.connect(('127.0.0.1', 8300))
        new_user_data = {'top_session':top_session, 'nick':nick}
        new_user_data = json.dumps(new_user_data)
        sock.send(new_user_data+'\n\n')
        res = sock.recv(128)
        sock.close()
        if 'success' not in res:
            raise Exception('recv from new user[%s] server: %s' %(nick, res))
    except Exception as e:
        print 'send user to gevent socket fail: %s' %(repr(e))


def batch_sync():
    m = pymongo.Connection(port=57324)
    db = m.taogold 
#"status" : "normal"
    cur = db.user.find(fields=['top_session', 'status'])
    for u in cur:
        if 'status' not in u or u['status']!='normal':
            continue
        sync_user(u['_id'], u['top_session'])


if __name__ == '__main__':
    batch_sync()


